package com.example.springbooteasycode.zjrc.project.Koal;

import java.io.*;
import java.net.*;
import java.util.Arrays;

/**
 * 我现在要把一串ASCII码，转为byte[]数组，通过tcp 发送给158.220.84.124 6000端口，java代码怎么写，并且打印请求返回
 */
public class TcpAsciiClient {
    public static void main(String[] args) {
//        String serverIp = "158.220.84.124";
//        int port = 6000;
        String serverIp = "127.0.0.1";
        int port = 8888;
        String asciiString = "Hello, Server!"; // 待发送的ASCII字符串

        try (Socket socket = new Socket(serverIp, port);
             OutputStream out = socket.getOutputStream();
             InputStream in = socket.getInputStream()) {

            // 将ASCII字符串转换为byte数组（使用US-ASCII编码）
            byte[] requestData = asciiString.getBytes("US-ASCII");

            // 打印byte[]数组
            System.out.println("使用Arrays.toString()打印：");
            System.out.println(Arrays.toString(requestData));

            //

            // 将byte[]数组输出到指定文件
            try (FileOutputStream fileOutputStream = new FileOutputStream("/Users/boykchen/Desktop/request.bin")) {
                fileOutputStream.write(requestData);
            }

            // 发送数据
            out.write(requestData);
            out.flush();
            System.out.println("已发送: " + asciiString);

            // 接收响应
            ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                responseBuffer.write(buffer, 0, bytesRead);
            }

            // 将响应转换为ASCII字符串并打印
            String response = responseBuffer.toString("US-ASCII");
            System.out.println("收到响应: " + response);

        } catch (UnknownHostException e) {
            System.err.println("服务器地址未知: " + serverIp);
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("通信异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
